const jwt = require('jsonwebtoken')
const { PRIVATE_KEY } = require('../config/screct')

class LoginController {
  sign(ctx, next) {
    // 1.获取用户信息
    const { id, account, identity_id } = ctx.user

    let token = ''
    // 2.颁发令牌token
    try {
      token = jwt.sign({
        id,
        account,
        roleId: identity_id
      },
      PRIVATE_KEY,
      {
        // expiresIn: 7 * 24 * 60 * 60 * 1000,
        expiresIn: '7d',
        algorithm: 'RS256'
      })
    } catch(error) {
      console.error('Error generating token: ', error)
    }

    // 3.返回用户信息
    ctx.body = {
      code: 0,
      message: '登录成功 ~',
      data: {
        token: token,
        id,
        account
      }
    }
  }

  test(ctx, next) {
    ctx.body = {
      code: 0,
      message: '验证身份通过 ~',
      data: ctx.user
    }
  }
}

module.exports = new LoginController()